<template>
  <el-form  label-width="120px" ref="form" :model="tag" :rules="rules">

    <el-form-item label="tag名称">
      <el-input v-model="tag.name"></el-input>
    </el-form-item>
    <el-form-item label="功能码">
      <el-select v-model="tag.func_code">
        <el-option 
          v-for="item in SYS_PARAMS.func_code"
          :key="item.name+item.name"
          :label="item.name"
          :value="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="寄存器起始地址">
      <el-input v-model="tag.register_start_address"></el-input>
    </el-form-item>
    <el-form-item label="寄存器个数">
      <el-input v-model="tag.register_num"></el-input>
    </el-form-item>
    <el-form-item label="倍率">
      <el-input v-model="tag.rate"></el-input>
    </el-form-item>
    <el-form-item label="读写标识">
      <el-select v-model="tag.control_type">
        <el-option 
          v-for="item in SYS_PARAMS.control_type"
          :key="item.name+item.name"
          :label="item.name"
          :value="item.name"
        ></el-option>
      </el-select>
    </el-form-item>
    <div class="form-button">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
    </div>
  </el-form>
</template>
<script>
import { mapGetters } from 'vuex'

import {
  addTagApi,
  updateTagApi
} from '@/api/setting'


export default {
  name: 'form-tag',
  props:{
    data: Object
  },
  computed: {
    ...mapGetters(['SYS_PARAMS'])
  },
  watch:{
    data:{
      immediate: true,
      handler(){
        this.tag = this.data;
        this.loading = false;
      }
    }
  },
  data(){
    return {
      tag: {
        name: '',
        func_code: '01',
        register_start_address: '',
        register_num: '',
        rate: '9600',
        control_type: 'RO',
      },
      rules: {

      },
      loading: false
    }
  },
  methods: {
    cancel(){
      this.$emit('close')
    },
    confirm(){
      this.$refs.form.validate( valid => {
        if(valid){
          this.loading = true;
          if(this.tag.id) this.updateTag();
          else this.addTag();
        }
      })
    },
     addTag(){
      addTagApi(this.tag).then(res => {
        this.loading = false;
        if(res.code == 0){
          this.$message({type: 'success', message: '提交成功'})
          this.$emit('refresh', {parent_id: this.tag.parent_id})
          this.$emit('close')
        }
      })
    },
    updateTag(){
      updateTagApi(this.tag).then(res => {
        this.loading = false;
        if(res.code == 0){
          this.$message({type: 'success', message: '提交成功'})
           this.$emit('refresh', {parent_id: this.tag.parent_id})
          this.$emit('close')
        }
      })
    }
  }

}
</script>
<style  scoped>
.form-button{
  margin-left: 30px;
  position: absolute;
  bottom: 20px;
}
</style>